package cn.yhjz.generator.controller;

import cn.yhjz.common.AjaxResponse;
import cn.yhjz.generator.entity.SysGenModel;
import cn.yhjz.generator.entity.SysGenModelProp;
import cn.yhjz.generator.service.ISysGenModelPropService;
import cn.yhjz.generator.service.ISysGenModelService;
import cn.yhjz.generator.vo.SysGenModelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/gen/model")
@Slf4j
public class SysGenModelController {

    @Autowired
    private ISysGenModelService sysGenModelService;

    @Autowired
    private ISysGenModelPropService sysGenModelPropService;

    @PostMapping("/list")
    public AjaxResponse list(@RequestBody SysGenModel sysGenModel) {
        return AjaxResponse.success(sysGenModelService.select(sysGenModel));
    }

    @PostMapping("/page")
    public AjaxResponse page(@RequestBody SysGenModelVo vo) {
        SysGenModel entity = new SysGenModel();
        BeanUtils.copyProperties(vo, entity);
        return AjaxResponse.success(sysGenModelService.getPage(vo.getCurrentPage(), vo.getPageSize(), entity));
    }

    @PostMapping("/getPropsByModelCode")
    public AjaxResponse getPropsByModelCode(String modelCode) {
        SysGenModelProp param = new SysGenModelProp();
        param.setModelCode(modelCode);
        List<SysGenModelProp> propList = sysGenModelPropService.select(param);

        return AjaxResponse.success(propList);
    }

    @GetMapping("/getModelInfoById")
    public AjaxResponse getModelInfoById(Long id) {
        SysGenModelVo model = this.sysGenModelService.selectById(id);
        SysGenModelProp param = new SysGenModelProp();
        param.setModelCode(model.getModelCode());
        List<SysGenModelProp> propList = sysGenModelPropService.select(param);
        model.setPropList(propList);
        return AjaxResponse.success(model);
    }

    @PostMapping("/addOrUpdate")
    public AjaxResponse add(@RequestBody SysGenModelVo entity) {
        if (entity.getId() != null) {
            return AjaxResponse.success(sysGenModelService.updateById(entity));
        } else {
            return AjaxResponse.success(sysGenModelService.insert(entity));
        }
    }



    @GetMapping("/selectById")
    public AjaxResponse selectById(Long id) {
        return AjaxResponse.success(sysGenModelService.selectById(id));
    }

    @DeleteMapping("/deleteById")
    public AjaxResponse deleteById(Long id) {
        return AjaxResponse.success(sysGenModelService.deleteById(id));
    }

    @PostMapping("/createBySql")
    public AjaxResponse createBySql(String sql) {
        log.info(sql);
        this.sysGenModelService.addFromSql(sql);
        return AjaxResponse.success();
    }
}
